<template>
    <div v-if="visible">
        <el-drawer title="分配班级" :append-to-body="true" :before-close="handleClose" :size="600" :visible.sync="visible"
            direction="rtl" custom-class="drawer" :destroyOnClose="true" ref="drawer">
            <div class="drawer__content" v-loading="loading">
                <el-row>

                    <el-form :model="formSearch" :rules="rules" ref="form">
                        <el-form-item>
                            <el-input placeholder="请输入班级名称" clearable="" v-model="formSearch.class_name"
                                class="input-with-select">
                                <el-button @click="search" slot="append" icon="el-icon-search"></el-button>
                            </el-input>
                        </el-form-item>
                    </el-form>

                    <el-form :model="formShow" :rules="rules" ref="form">
                        <el-form-item prop="nickname" label="员工姓名:" size="mini">
                            {{ formShow.realname }}
                        </el-form-item>
                        <el-form-item prop="class_id-s" label="当前班级:" size="mini">
                            <div v-if="formShow.class_names">
                                <div v-for="(item, index) in formShow.class_names" :key="index" style="display: inline-block;">
                                    <span>
                                        {{ item }}
                                    </span>
                                        <span @click="cancelClass(item)">
                                        <i class="el-icon-close"></i>
                                    </span>
                                </div>
                            </div>
                        </el-form-item>
                    </el-form>
                </el-row>

                <el-row>
                  <el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" row-key="id"
                            style="width: 100%"  @selection-change="handleSelectionChange">
<!--                    <el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" row-key="id"-->
<!--                        style="width: 100%" @selection-change="handleSelectionChange" @select="handleSelect">-->
                        <el-table-column type="selection" width="55">
                        </el-table-column>
                        <el-table-column prop="class_name" label="班级名称" width="120" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column prop="create_user_name" label="创建人">
                        </el-table-column>
                        <el-table-column prop="student_num" label="学员数">
                        </el-table-column>
                    </el-table>

                    <div class="block">

                        <el-pagination @current-change="handleCurrentChange" :current-page="pageInfo.pageNumber"
                                       :page-size="pageInfo.pageSize" background layout="total, prev, pager, next"
                                       :total="pageInfo.total">
                        </el-pagination>
                    </div>
                    
                </el-row>

                <div class="drawer__footer">
                    <el-button @click="cancelForm" size="mini">取 消</el-button>
                    <el-button type="primary" size="mini" @click="handleSubmit">保存</el-button>
                </div>
            </div>

        </el-drawer>
    </div>
</template>
<script>
import { list,isCanDel } from '@/api/kanke/gradeclass/gradeclass';
import {getTeacherDetail,allocate} from "@/api/kanke/teacher/teacher";
import {getStudentList} from "@/api/kanke/student";

export default {
    name: 'KanKe-AssignClass',
    props: {
        visible: {
            type: Boolean,
        },
        id: {
            //type: Number,
            default: 0
        },
        handleReload: {
            type: Function
        }
    },
    data() {
        return {
            loading: false,
            form: {
                class_id: '',
            },
            rules: {
            },
            formLabelWidth: '100px',
            dialog: true,
            tableData: [],
            formSearch: {},
            formShow: {
                id: 0,
                class_names: '',
                class_ids: '',
            },
            pageInfo: {
                pageNumber: 1,
                pageSize: 10
            },
            class_list: [],
            // 选中的班级
            multipleSelection: [],
            gotoDel:true
        }
    },
    watch: {
        id: {
            handler(newVal) {
                if (newVal) {
                    this.init()
                }
            },
            immediate: true
        }
    },
    methods: {
        init() {
            this.loading = true
            list({ ...this.formSearch, ...this.pageInfo }).then(res => {
                if (res.code == 200) {
                    this.tableData = res.data.list
                    this.pageInfo.total = res.data.total
                    getTeacherDetail({id:this.id}).then(res => {
                        if (res.code == 200) {
                            console.log('res',res);
                            this.formShow.id = res.data.id
                            this.formShow.realname = res.data.realname
                            this.formShow.class_ids = res.data.class_ids
                            this.formShow.class_names = res.data.class_names
                            this.tableData.forEach(row => {
                                if(res.data.class_ids.includes(row.id)){
                                    this.$refs.multipleTable.toggleRowSelection(row, true);
                                }
                            });
                            this.multipleSelection=this.formShow.class_ids;
                        }
                    })
                    // this.$nextTick(() => {
                    //     this.setDefaultSelections();
                    // });
                }
                this.loading = false
            })
        },
        handleSelect(selection,row){
            console.log('select banji--1',selection);
            console.log('select banji--2',row);
            if(this.formShow.class_ids.includes(row.id)){

                this.formShow.class_ids.splice(this.formShow.class_ids.indexOf(row.id),1);
                this.formShow.class_names.splice(this.formShow.class_names.indexOf(row.class_name),1);

            }else{
              this.formShow.class_ids.push(row.id);
              this.formShow.class_names.push(row.class_name);
            }
        },
        setDefaultSelections() {
            // 默认勾选所有行
            this.tableData.forEach(row => {
                this.$refs.multipleTable.toggleRowSelection(row, true);
            });
        },
        handleClose(done) {
            this.$emit('update:visible', false);
        },
        handleSelectionChange(val) {
            console.log('当前选中行',val);
            this.formShow.class_ids = [];
            this.formShow.class_names = [];
            if(val){
                for(let i=0;i<val.length;i++){

                    this.formShow.class_ids.push(val[i].id);
                    this.formShow.class_names.push(val[i].class_name);

                }
            }
            this.multipleSelection = val
        },
        cancelForm() {
            this.$emit('update:visible', false);
        },
        handleSubmit() {
            const params = {
                teacher_id: this.formShow.id,
                class_ids: this.formShow.class_ids
            }
            allocate(params).then(res => {
                if (res.code == 200) {
                    this.$emit('update:visible', false);
                    this.$message.success(res.msg)
                    this.$emit('handleReload')
                }else{
                    
                }
            })
        },
        search() {
          this.init();
            // this.loading = true
            // this.pageInfo.pageNumber = 1
            // list({ ...this.formSearch, ...this.pageInfo }).then(res => {
            //     if (res.code == 200) {
            //         this.tableData = res.data.list
            //         this.pageInfo.total = res.data.total
            //     }
            //     this.loading = false
            // })
        },
        handleCurrentChange(e) {
            this.pageInfo.pageNumber = e;
            this.init();
        },
        async cancelClass(class_name) {
            let class_id = 0;
            for(let i=0;i<this.tableData.length;i++){
                if(this.tableData[i].class_name == class_name){
                    class_id = this.tableData[i].id;
                    break;
                }
            }
            //判断是否可以删除
            await isCanDel({type:2,teacher_id:this.id,class_id:class_id}).then((res) => {
                if(res.code == 200){
                    if(!res.data){
                        this.$message({type: 'error', message: '该老师已分配的班级里有学生且是唯一的老师，无法删除！'});
                        this.gotoDel = false;
                    }
                }else{
                    this.$message({type: 'warning', message: res.msg});
                    this.gotoDel = false;
                }
            });
            if(!this.gotoDel){
                return
            }
            let arr_class_ids = this.formShow.class_ids;
            let arr_class_names = this.formShow.class_names;

            this.formShow.class_ids = arr_class_ids.filter(item=>item !== class_id);
            this.formShow.class_names = arr_class_names.filter(item=> item !== class_name);
            this.tableData.forEach(row => {
                if(class_id == row.id){
                    this.$refs.multipleTable.toggleRowSelection(row, false);
                }
            });
        }
    }
}
</script>
<style lang="scss" scoped>
.drawer {
    &__content {
        padding: 20px;
        margin-bottom: 30px;

        ::v-deep .el-select .el-input {
            width: 200px;
        }

        ::v-deep .el-icon-close {
            padding-left: 10px;
        }
    }

    &__footer {
        margin-top: 20px;
        margin-left: 50px;
    }
}
</style>